package main

import (
	"context"
	"fmt"
	helloworldpb "go_stu/my_grpc_gateway/protos/gen/go"

	"github.com/hashicorp/consul/api"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

// 默认方式请求rpc
func Client() {
	conn, err := grpc.Dial("127.0.0.1:8091", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic(err.Error())
	}
	defer conn.Close()
	c := helloworldpb.NewGreeterClient(conn)
	r, err := c.SayHello(context.Background(), &helloworldpb.HelloRequest{Name: "absw1"})
	if err != nil {
		panic(err.Error())
	}
	fmt.Println(r.Message)
}

// 使用consul获取rpc
func ClientConsul() {
	// 获取consul的连接
	consulClient, err := api.NewClient(api.DefaultConfig())
	if err != nil {
		panic(err.Error())
	}

	// 获得健康的服务
	service, _, err := consulClient.Health().Service("Greeter", "grpc", true, nil)
	if err != nil {
		panic(err.Error())
	}
	// 获取地址
	addr := fmt.Sprintf("%v:%v", service[0].Service.Address, service[0].Service.Port)

	// grpc远程调用
	grpcConn, _ := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	grpcClient := helloworldpb.NewGreeterClient(grpcConn)
	defer grpcConn.Close()
	// 调用
	res, _ := grpcClient.SayHello(context.Background(), &helloworldpb.HelloRequest{Name: "Amyya"})
	fmt.Println("grpc 调用成功：", res.Message)
}

func main() {
	// ClientConsul()
	Client()
}
